#include <iostream>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

//模拟抢票环境，体现线程的互斥的现象
int ticket = 1000;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;;

void* routine(void* argc)
{

    char* id = static_cast<char*>(argc);

    while(true)
    {
        //注意锁放到位置，这也很重要S
        pthread_mutex_lock(&lock);
        if(ticket > 0)
        {
            //临界区
            usleep(1000);
            ticket--;
            std::cout << id << " sell the tickets; ticket numble: " << ticket << std::endl;
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        } 

    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, nullptr, routine, (void*)"thread-1");
    pthread_create(&t2, nullptr, routine, (void*)"thread-2");
    pthread_create(&t3, nullptr, routine, (void*)"thread-3");
    pthread_create(&t4, nullptr, routine, (void*)"thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}